package com.ygqh.baby.controller.admin;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.foxinmy.weixin4j.util.StringUtil;
import com.ygqh.baby.ao.DataStatus;
import com.ygqh.baby.ao.Message;
import com.ygqh.baby.ao.QueryInfo;
import com.ygqh.baby.ao.ResultSet;
import com.ygqh.baby.controller.utils.DocumentHandler;
import com.ygqh.baby.model.AdminSkuSearchReq;
import com.ygqh.baby.model.AdminSkuSearchVo;
import com.ygqh.baby.po.*;
import com.ygqh.baby.service.*;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.krysalis.barcode4j.impl.code128.Code128Bean;
import org.krysalis.barcode4j.output.bitmap.BitmapCanvasProvider;
import org.krysalis.barcode4j.tools.UnitConv;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author ZhangSai
 * @date 2016/11/4 0004
 */
@Controller
@RequestMapping("/admin/adminsku")
public class AdminSkuConstroller extends BaseController<Object, java.lang.Long> {
    @Autowired
    private AdminSkuService adminSkuService;
    @Autowired
    private FileService fileService;
    @Autowired
    private YgMaterialService ygMaterialService;
    @Autowired
    private YgCategoryService ygCategoryService;
    @Autowired
    private YgAttributeService ygAttributeService;

    @RequestMapping("searchSku")
    @ResponseBody
    public Map<String, Object> searchSku(String q, QueryInfo queryInfo, Long groupId, String productCode) {

        ResultSet<AdminSku> resultSet = adminSkuService.search(queryInfo, q, groupId, productCode);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("searchSkuCost")
    @ResponseBody
    public Map<String, Object> searchSkuCost(String productName, String productCode, String skuCode, QueryInfo queryInfo, Long groupId) {

        ResultSet<AdminSku> resultSet = adminSkuService.searchByProduct(queryInfo, productName, productCode, skuCode, groupId);

        return resultSet.toDatatables(null);
    }

    @RequestMapping("saveSku")
    @ResponseBody
    public Message saveSku(String sku, int groupCode, Long groupId) {
        List<AdminSku> adminsku = JSON.parseObject(sku, new TypeReference<List<AdminSku>>() {
        });
        adminSkuService.saveBatch(adminsku, groupCode, getSession().getTrueName(), groupId);
        return SUCCESS_MESSAGE;

    }

    @RequestMapping("getSkuList")
    @ResponseBody
    public List<AdminSku> getSkuList(String productCode) {
        return adminSkuService.find(productCode);
    }

    @RequestMapping("updateSkuStatus")
    @ResponseBody
    public Message updateSkuStatus(String productCode) {
        return adminSkuService.updateProduct(productCode, DataStatus.Delete.name()) > 0 ? SUCCESS_MESSAGE : ERROR_MESSAGE;

    }

    @RequestMapping("exportSku")
    public void exportSku(String q, Long groupId, HttpServletRequest request, HttpServletResponse response) throws IOException {

        List<AdminSku> list = adminSkuService.find(q, groupId);
        downloadSku(list, request, response);
    }

    @RequestMapping("exportBarCode")
    public void exportBarCode(String q, Long groupId, HttpServletRequest request, HttpServletResponse response) throws IOException {
        try {
            Code128Bean code128 = new Code128Bean();
            final int dpi = 100;
            //Configure the barcode generator
            double d = UnitConv.in2mm(1.0f / dpi);
            System.err.println(d);
            code128.setModuleWidth(0.5); //makes the narrow bar
            // code128.setFontName("");
            code128.setFontSize(4);
            System.err.println(code128.getFontName());
            System.err.println(code128.getFontSize());
            code128.doQuietZone(true);
            code128.setQuietZone(0.5);
            //Open output file
            File outputFile = new File("D:/imageUploadTempUrl/1.png");
            OutputStream out = new FileOutputStream(outputFile);
            try {
                //Set up the canvas provider for monochrome JPEG output
                BitmapCanvasProvider canvas = new BitmapCanvasProvider(
                        out, "image/png", dpi, BufferedImage.TYPE_BYTE_BINARY, false, 0);

                //Generate the barcode
                code128.generateBarcode(canvas, "110024020");

                //Signal end of generation
                canvas.finish();
            } finally {
                out.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }


    }

    @RequestMapping("readTemplate")
    @ResponseBody
    public Message readTemplate(@RequestParam("uploadFile") MultipartFile uploadFile, HttpServletRequest request, HttpServletResponse response) throws IOException {
        InputStream is = uploadFile.getInputStream();
        XSSFWorkbook xssfWorkbook = new XSSFWorkbook(is);
        Map map = new HashMap();
        List<AdminSku> skuList = new ArrayList<>();
        List<String> skuCodeList = new ArrayList<>();
        Map<String, Boolean> gostList = new HashMap<String, Boolean>();
        try {
            // Read the Sheet
            for (int numSheet = 0; numSheet < xssfWorkbook.getNumberOfSheets(); numSheet++) {
                XSSFSheet xssfSheet = xssfWorkbook.getSheetAt(numSheet);
                if (xssfSheet == null) {
                    continue;
                }
                // Read the Row
                for (int rowNum = 1; rowNum <= xssfSheet.getLastRowNum(); rowNum++) {
                    XSSFRow xssfRow = xssfSheet.getRow(rowNum);
                    if (xssfRow == null) {
                        continue;
                    }
                    if (xssfRow != null) {
                        AdminSku model = new AdminSku();
                        XSSFCell groupName = xssfRow.getCell(0);
                        XSSFCell productName = xssfRow.getCell(1);
                        XSSFCell color = xssfRow.getCell(2);
                        XSSFCell size = xssfRow.getCell(3);
                        XSSFCell coats = xssfRow.getCell(4);
                        //分类
                        XSSFCell category = xssfRow.getCell(5);
                        //商品属性
                        XSSFCell basicAttr = xssfRow.getCell(6);
                        //销售价
                        XSSFCell salePrice = xssfRow.getCell(7);
                        //衣服成本
                        XSSFCell skuPrice = xssfRow.getCell(8);
                        //包装袋名称
                        XSSFCell baozhuangdai = xssfRow.getCell(9);
                        //封口贴
                        XSSFCell fengkoutie = xssfRow.getCell(10);
                        //贴纸
                        XSSFCell tiezhi0 = xssfRow.getCell(11);
                        XSSFCell tiezhi1 = xssfRow.getCell(12);
                        XSSFCell tiezhi2 = xssfRow.getCell(13);
                        XSSFCell tiezhi3 = xssfRow.getCell(14);
                        XSSFCell tiezhi4 = xssfRow.getCell(15);
                        XSSFCell tiezhi5 = xssfRow.getCell(16);
                        XSSFCell tiezhi6 = xssfRow.getCell(17);

                        List<String> materialList = new ArrayList<String>();
                        String baozhuangDesc = getValue(baozhuangdai);
                        String fengkouDesc = getValue(fengkoutie);
                        materialList.add(baozhuangDesc);
                        materialList.add(fengkouDesc);
                        Map<String, Object> tiezhiMap = new HashMap<String, Object>();
                        tiezhiMap.put("条形码贴纸", getValue(tiezhi0));
                        tiezhiMap.put("1号贴纸", getValue(tiezhi1));
                        tiezhiMap.put("2号贴纸", getValue(tiezhi2));
                        tiezhiMap.put("3号贴纸", getValue(tiezhi3));
                        tiezhiMap.put("4号贴纸", getValue(tiezhi4));
                        tiezhiMap.put("5号贴纸", getValue(tiezhi5));
                        tiezhiMap.put("6号贴纸", getValue(tiezhi6));
                        BigDecimal costPrice = new BigDecimal(0);
                        JSONObject jsonObj = new JSONObject();
                        String r = "";//字段借用一下
                        String categoryName = getValue(category);
                        Long categoryId = null;
                        //获取分类
                        YgCategory cate = ygCategoryService.findByCategoryName(categoryName, 3L);
                        if (cate != null) {
                            categoryId = cate.getId();
                        } else {
                            r += categoryName + "不存在";
                        }
                        //判断后台属性
                        String sAttr = getValue(basicAttr);
                        String[] sAttrArray = null;
                        if (sAttr != null && !sAttr.equals("")) {
                            sAttrArray = sAttr.split(",");
                        }
                        if (sAttrArray.length > 0) {

                            List<YgAttribute> list = ygAttributeService.findByParentId(15L);
                            boolean isE = false;
                            for (String s : sAttrArray) {
                                isE = false;
                                for (YgAttribute a : list) {
                                    if (a.getAttributeName().equals(s)) {
                                        isE = true;
                                        break;
                                    }
                                }
                            }
                            if (!isE) r += "商品属性不存在";
                        } else {
                            r += "商品属性不存在";
                        }


                        List<Map<String, Object>> tiezhi = new ArrayList<Map<String, Object>>();

                        //判断包装袋  封口贴 贴纸是否存在
                        List<YgMaterial> listMaterial = ygMaterialService.findByNameList(materialList);
                        //如果数据全部存在 则获取价格
                        Map<String, Object> temp = new HashMap<String, Object>();
                        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
                        if (listMaterial != null) {
                            for (YgMaterial ygm : listMaterial) {
                                temp = new HashMap<String, Object>();
                                list = new ArrayList<Map<String, Object>>();
                                if (ygm.getCategoryName().equals("包装袋") && materialList.indexOf(ygm.getMaterialName()) > -1) {
                                    temp.put("id", ygm.getId());
                                    temp.put("price", ygm.getPrice());
                                    jsonObj.put("baozhuang", temp);
                                    costPrice = costPrice.add(ygm.getPrice());
                                }
                                if (ygm.getCategoryName().equals("封口贴") && materialList.indexOf(ygm.getMaterialName()) > -1) {
                                    temp.put("id", ygm.getId());
                                    temp.put("price", ygm.getPrice());
                                    jsonObj.put("fengkou", temp);
                                    costPrice = costPrice.add(ygm.getPrice());
                                }
                                if (ygm.getCategoryName().equals("贴纸") && tiezhiMap.containsKey(ygm.getMaterialName()) && tiezhiMap.get(ygm.getMaterialName()) != null) {
                                    temp.put("id", ygm.getId());
                                    temp.put("price", ygm.getPrice());
                                    temp.put("amount", tiezhiMap.get(ygm.getMaterialName()));
                                    tiezhi.add(temp);

                                    costPrice = costPrice.add(ygm.getPrice().multiply(new BigDecimal(tiezhiMap.get(ygm.getMaterialName()).toString())));

                                }


                            }

                            jsonObj.put("tiezhi", tiezhi);
                        }

                        if (!jsonObj.containsKey("baozhuang") && baozhuangDesc != null && baozhuangDesc.length() > 1)
                            r += baozhuangDesc + "不存在";
                        if (!jsonObj.containsKey("fengkou") && fengkouDesc != null && fengkouDesc.length() > 1)
                            r += fengkouDesc + "不存在";
                        String p = getValue(skuPrice);
                        jsonObj.put("skuCost", p);

                        costPrice = costPrice.add((p == null ? new BigDecimal(0) : new BigDecimal(p)));

                        model.setColor(getValue(color));
                        YgGroup group = new YgGroup();
                        group.setGroupName(getValue(groupName));
                        group.setCostPrice(costPrice);
                        group.setCreateBy(baozhuangDesc);//包装袋
                        group.setUpdateBy(fengkouDesc);//封口贴
                        group.setBasicAttribute(sAttr);
                        group.setCategoryId(categoryId);

                        group.setExtMaterial(jsonObj.toJSONString());
                        model.setIsCoats(getValue(coats).equals("是") ? true : false);
                        model.setGroup(group);
                        model.setProductName(getValue(productName));
                        model.setSizeName(getValue(size));
                        String valueOfSalePrice = getValue(salePrice);
                        if (StringUtil.isBlank(valueOfSalePrice)) {
                            r += "销售价不能为空；";
                        } else {
                            model.setSalePrice(new BigDecimal(valueOfSalePrice));
                        }


                        if (model.getGroup().getGroupName() == null)
                            r += "款式名称不能为空";
                        if (r != "") {
                            model.setCreateBy(r);
                            skuList.add(model);
                            continue;
                        }
                        if (model.getProductName() == null)
                            r += "商品名称不能为空";
                        if (model.getColor() == null)
                            r += "颜色不能为空";
                        if (model.getSizeName() == null || model.getSizeName().length() == 0)
                            r += "尺码不能为空";
                        //检查数据是否存在
                        AdminSku s = adminSkuService.selectSkuByName(model.getGroup().getGroupName(), model.getProductName(), model.getColor(), model.getSizeName());
                        if (s != null)
                            r += "数据已经存在";
                        String productCode = model.getGroup().getGroupName() + model.getColor() + model.getSizeName();
                        if (skuCodeList.contains(productCode)) {
                            r += "商品信息重复";
                        } else {
                            skuCodeList.add(productCode);
                        }
                        //相同的款式名称+相同的颜色+相同的名称 gost 标示要一致
                        String gost = model.getGroup().getGroupName() + model.getProductName() + model.getColor();
                        if (gostList.containsKey(gost) && !gostList.get(gost).equals(model.getIsCoats())) {
                            r += "GOTS认证不一致";
                        } else {
                            gostList.put(gost, model.getIsCoats());
                        }


                        model.setCreateBy(r);
                        skuList.add(model);

                    }
                }
            }
            return Message.success(skuList);
        } catch (Exception e) {
            logger.error("readTemplate error-> {}", e.getMessage(), e);
            return Message.error(e.getMessage(), skuList);
        }
    }

    @SuppressWarnings("static-access")
    private String getValue(XSSFCell hssfCell) {
        if (hssfCell == null)
            return null;
        if (hssfCell.getCellType() == hssfCell.CELL_TYPE_BOOLEAN) {
            // 返回布尔类型的值
            return String.valueOf(hssfCell.getBooleanCellValue());
        } else if (hssfCell.getCellType() == hssfCell.CELL_TYPE_NUMERIC) {
            DecimalFormat df = new DecimalFormat("0");
            String str = df.format(hssfCell.getNumericCellValue());
            // 返回数值类型的值
            return str;
        } else {
            // 返回字符串类型的值
            return String.valueOf(hssfCell.getStringCellValue());
        }
    }

    @RequestMapping("saveBatchSku")

    public void saveBatchSku(String sku, HttpServletRequest request, HttpServletResponse response) {
        List<AdminSku> adminsku = JSON.parseObject(sku, new TypeReference<List<AdminSku>>() {
        });
        List<AdminSku> newlist = adminSkuService.saveBatchSku(adminsku, getSession().getTrueName());
        downloadSku(newlist, request, response);

    }

    private void downloadSku(List<AdminSku> list, HttpServletRequest request, HttpServletResponse response) {
        byte[] bytes = fileService.downloadFromOss("template/skulist.xls");
        // ByteToInputStream.input2byte(inputStream);
        List<Map<String, Object>> dataMaps = new ArrayList<Map<String, Object>>();
        Map<String, Object> dataMap = new HashMap<String, Object>();

        dataMap.put("resultSet", list);
        dataMaps.add(dataMap);
        DocumentHandler.DownloadExcel(bytes, "SKU数据.xls", dataMap, request, response);
    }

    /**
     * 商家编码列表查询（第二版）
     *
     * @param searchReq 查询条件
     * @return
     * @date 2019-02-27 11:55
     */
    @RequestMapping("searchSkuV2")
    @ResponseBody
    public Map<String, Object> searchSku(QueryInfo queryInfo, AdminSkuSearchReq searchReq) {
        searchReq.setStart(queryInfo.getStart());
        searchReq.setEnd(queryInfo.getEnd());
        ResultSet<AdminSkuSearchVo> resultSet = adminSkuService.searchSku(searchReq);
        return resultSet.toDatatables(null);
    }

    /**
     * 推送商家编码信息到旺店通货品档案
     *
     * @param productCode 商品编码
     * @return
     * @date 2019-02-27 17:26
     */
    @RequestMapping("pushAdminSkuToWdtGoods")
    @ResponseBody
    public Message pushAdminSkuToWdtGoods(@RequestParam String productCode) {
        return adminSkuService.pushAdminSkuToWdtGoods(productCode);
    }

}
